import utils from "@/utils/utils.js";

export default {
  //获取定位
  getLocation(context) {
    return new Promise((resolve, reject) => {
      mapSelect()
      function mapSelect(params) {
        uni.getLocation({
          type: 'gcj02',
          success: res => {
            let location = {
              latitude: res.latitude,
              longitude: res.longitude
            }
            //console.log("uniapp自带获取", location)
            //uni.setStorageSync('location', location)
            resolve(location)
          },
          fail: async (e) => {
            getMapLocation()
          }
        })
      }
      async function getMapLocation() {
        uni.getSetting({
          success: async (res) => {
            var status = res.authSetting
            if (!status['scope.userLocation']) {
              // 如果授权信息中没有地理位置的授权，则需要弹窗提示用户需要授权地理信息
              let resp = await utils.showModal({ title: '是否授权当前位置', content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用' })
              if (!resp) return
              uni.openSetting({
                success: (data) => {
                  // 如果用户授权了地理信息在，则提示授权成功
                  if (data.authSetting['scope.userLocation'] === true) {
                    utils.showToast("授权成功", 1)
                    // 授权成功后，然后再次chooseLocation获取信息
                    mapSelect()
                  } else {
                    utils.showToast("授权失败")
                  }
                },
              })
            }
          },
          fail: () => {
            utils.showToast("调用授权窗口失败")
          },
        })
      }
    })
  },

  //登录
  login(context, univerifyStyle) {
    return new Promise((resolve, reject) => {
      let obj = {
        provider: context ? context : 'weixin',
        success: (res) => {
          if (res.code) {
            resolve(res.code)
          } else {
            resolve(res.authResult)
          }
        },
        fail: err => {
          // uni.$uv.toast(err)
          reject(err.errMsg)
        }
      }
      // #ifdef APP-PLUS
      obj.onlyAuthorize = true
      if (univerifyStyle) obj.univerifyStyle = univerifyStyle
      // #endif
      uni.login(obj)
    })
  },

  //上传图片
  chooseImage(context) {
    return new Promise((resolve, reject) => {
      uni.chooseImage({
        count: context ? context : 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: res => {
          resolve(res.tempFilePaths)
        }
      })
    })
  },

  //上传视频
  chooseVideo(context) {
    return new Promise((resolve, reject) => {
      uni.chooseVideo({
        count: 1,
        sourceType: ['camera', 'album'],
        compressed: false,
        success: res => {
          if (res.duration > 15) {
            return uni.$uv.toast("上传的视频时长不超过15s")
          }
          resolve(res.tempFilePath)
        }
      })
    })
  },

  //本地图片转成base64
  transBase64(context) {
    return new Promise((resolve, reject) => {
      // #ifdef H5
      uni.request({
        url: context,
        method: 'GET',
        responseType: 'arraybuffer',
        success: res => {
          let base64 = uni.arrayBufferToBase64(res.data); //把arraybuffer转成base64
          base64 = 'data:image/png;base64,' + base64;
          resolve(base64)
        }
      })
      // #endif

      // #ifdef MP-WEIXIN
      uni.getFileSystemManager().readFile({
        filePath: context, //选择图片返回的相对路径
        encoding: 'base64', //编码格式
        success: res => { //成功的回调
          let path = 'data:image/png;base64,' + res.data
          resolve(path)
        }
      })
      // #endif

      // #ifdef APP-PLUS
      plus.io.resolveLocalFileSystemURL(url, (entry) => {
        entry.file((file) => {
          let fileReader = new plus.io.FileReader();
          if (file.size > 450 * 1024) {
            return uni.showToast({
              title: '图片大小不能超过450k',
              icon: 'none'
            })
          }
          fileReader.onloadend = (e) => {
            resolve(e.target.result)
          };
          fileReader.readAsDataURL(file);
        })
      })
      // #endif
    })
  },

  //打开地图，选择位置
  chooseLocation(context) {
    return new Promise((resolve, reject) => {
      uni.chooseLocation({
        success: (res) => {
          resolve(res)
        },
        fail: (res) => {
          reject(res.errMsg)
        }
      });
    })
  },

  //获取服务供应商
  getProvider(service) {
    return new Promise((resolve, reject) => {
      uni.getProvider({
        service,
        success: (res) => {
          resolve(res.provider)
        },
        fail: (res) => {
          reject(res.errMsg)
        }
      });
    })
  },

  //预登录。用于App手机号一键登录
  preLogin(provider) {
    return new Promise((resolve, reject) => {
      uni.preLogin({
        provider,
        success(res) {
          console.log('预登录成功', res);
          resolve(true)
        },
        fail(err) {
          console.log("号称", err.errMsg)
          utils.showToast(err.errMsg)
          reject(err.errMsg)
        }
      })
    })
  },

  //获取图片信息
  getImageInfo(context) {
    return new Promise((resolve, reject) => {
      uni.getImageInfo({
        src: context,
        success: function(image) {
          resolve(image)
        }
      });
    })
  },
  //把网络图片改成本地图片
  getNetworkImage(url) {
    return new Promise((resolve, reject) => {
      uni.downloadFile({
        url,
        success: (e) => {
          resolve(e)
        }
      })
    })
  },

  //预览图片
  previewImage(imgcont, index) {
    uni.previewImage({
      current: index,
      urls: imgcont,//['你的图片地址']
      indicator: "number",
      loop: true,
    });
  },

  //系统信息
  getSystemInfo(url) {
    return new Promise((resolve, reject) => {
      uni.getSystemInfo({
        success: function(res) {
          resolve(res)
        }
      });
    })
  },

  //获取cid
  getCidAsync() {
    return new Promise((resolve, reject) => {
      // 获取客户端推送信息
      plus.push.getClientInfoAsync(function(clientInfo) {
        // 获取CID
        var cid = clientInfo.clientid;
        // 调用resolve方法返回CID
        resolve(cid);
      }, function(error) {
        // 获取CID失败，调用reject方法返回错误信息
        reject(error);
      });
    })
  },

  //扫码
  scanCode() {
    return new Promise((resolve, reject) => {
      uni.scanCode({
        success: (res) => {
          resolve(res)
        },
        // 失败回调
        fail: (res) => {
          console.log('调用失败!')
        }
      });
    })
  },

  //判断当前环境
  getCurrentEnvironment(context) {
    return new Promise((resolve, reject) => {
      uni.getSystemInfo({
        success: function(res) {
          const platform = res.platform.toLowerCase();
          if (platform === 'devtools') {
            resolve('web');
          } else if (platform === 'ios' || platform === 'android') {
            resolve('app');
          } else if (platform === 'wechat') {
            resolve('wechat');
          } else {
            reject('无法确定当前环境');
          }
        },
        fail: function(error) {
          reject(error);
        }
      })
    });
  },


  //打电话
  makePhoneCall(context) {
    return new Promise((resolve, reject) => {
      uni.makePhoneCall({
        // 手机号
        phoneNumber: context,
        // 成功回调
        success: (res) => {
          console.log('调用成功!')
        },
        // 失败回调
        fail: (res) => {
          console.log('调用失败!')
        }
      });
    })
  },

  //打开地址
  openLocation(context) {
    return new Promise((resolve, reject) => {
      uni.openLocation({
        latitude: Number(context.lat ? context.lat : context.latitude),
        longitude: Number(context.lng ? context.lng : context.longitude),
        scale: 15,
        name: context.name
      });
    })
  },

  //复制粘贴
  setClipboardData(context) {
    return new Promise((resolve, reject) => {
      uni.setClipboardData({
        data: context.toString(),
        success: () => {
          uni.showToast({
            title: '复制成功',
            duration: 1500,
            icon: 'success'
          });
        }
      });
    })
  }
}



















